# -*- coding: utf-8 -*-
"""
Created on Sat Jun 28 11:21:17 2014

@author: Adrien
"""

import xlrd
import DatabaseHandlerInterface as DBHi
import Tkinter
import ttk
import tkFileDialog
import DataModel as Model

class PODown(DBHi.DatabasePluginInterface):
    
     def __init__(self):
        self._options={'path':''}
        self._data=None
        self._headers=[]
        self._diseases=[]
     
     def setConfigDoneFunction(self,func):
        self.configDoneFunction=func
    
     def getData(self):
         if self._data==None:
             self.readFile()
         return self._data
     
     def setDiseasesList(self,diseases):
         self._diseases=diseases
         
     def readFile(self):
        filePath=self._options['path']
        try:
         	book= xlrd.open_workbook(filePath)
        except:
		raise Exception('cannot open file')
        else:
            self._data={'genes':[],'fusions':[]}
            pubMedSheet=book.sheet_by_name('PubMed')
            omimSheet = book.sheet_by_name('OMIM')
            sangerSheet = book.sheet_by_name('SangerCGP')
            mitelmanSheet = book.sheet_by_name('Mitelman')
            _dataMitelman=self.extractDataFromMitelman(mitelmanSheet)
            _dataSanger= self.extractDataFromSanger(sangerSheet)
            _dataOMIM=self.extractDataFromOMIM(omimSheet)
            _dataPubMed=self.extractDataFromPubMed(pubMedSheet)
            import heapq
            from collections import OrderedDict
            result=list(heapq.merge(_dataMitelman['fusions'],_dataSanger['fusions'],_dataOMIM['fusions'],_dataPubMed['fusions']))
            self._data['fusions']=list(OrderedDict.fromkeys(result))
            result=list(heapq.merge(_dataMitelman['genes'],_dataSanger['genes'],_dataOMIM['genes'],_dataPubMed['genes']))
            self._data['genes']=list(OrderedDict.fromkeys(result))
        return self._data
    
    
     def extractDataFromMitelman(self,sheet):
         num=0
         _data={'genes':[],'fusions':[]}
         for rownum in range(sheet.nrows):
                myRow = sheet.row_values(rownum)
                if num <1:
                    self._headers.append(myRow)
                else:
                    import re
                    pattern=re.compile('(.*?)[q|p]')
                    m = pattern.match(myRow[2])
                    if m !=None:
                         chromosomeA = m.group(1)
                    else:
                        chromosomeA = myRow[2]
                    m = pattern.match(myRow[5])
                    if m !=None:
                         chromosomeB = m.group(1)
                    else:
                        chromosomeB = myRow[5]
                    geneA =Model.Gene(myRow[0],function="",chromosome=chromosomeA,disease="",locus=myRow[2])
                    geneB =Model.Gene(myRow[3],function="",chromosome=chromosomeB,disease="",locus=myRow[5])
                    _data['genes'].append(geneA)
                    _data['genes'].append(geneB)
                    fusion = Model.Fusion(myRow[0],myRow[3],breakpointA="", fusionDirectionA="",breakpointB="", strandB="", fusionDirectionB="",notes=myRow[8])
                    _data['fusions'].append(fusion)
                num+=1
         _data['genes']=sorted(_data['genes'], key=lambda gene: gene.name)
         _data['fusions']=sorted(_data['fusions'], key=lambda fusion: fusion.geneA)
         return _data
     
     def extractDataFromSanger(self,sheet):
         _data={'genes':[],'fusions':[]}
         num=0
         for rownum in range(sheet.nrows):
                myRow = sheet.row_values(rownum)
                if num <1:
                    self._headers.append(myRow)
                else:
                    import re
                    pattern=re.compile('(.*?)[q|p]')
                    m = pattern.match(str(myRow[2]))
                    if m !=None:
                         chromosomeA = m.group(1)
                    else:
                        chromosomeA = myRow[2]
                    m = pattern.match(str(myRow[6]))
                    if m !=None:
                         chromosomeB = m.group(1)
                    else:
                        chromosomeB = myRow[5]
                    diseaseA=""
                    diseaseB=""
                    for disease in self._diseases:
                        if myRow[3].find(disease)!=-1:
                            diseaseA+= disease + " "
                        if myRow[7].find(disease)!=-1:
                            diseaseB+= disease + " "
                    geneA =Model.Gene(myRow[0],function=myRow[3],chromosome=chromosomeA,disease=diseaseA,locus=myRow[2])
                    geneB =Model.Gene(myRow[4],function=myRow[7],chromosome=chromosomeB,disease=diseaseB,locus=myRow[6])
                    
                    _data['genes'].append(geneA)
                    _data['genes'].append(geneB)
                    fusion = Model.Fusion(myRow[0],myRow[4],breakpointA="", fusionDirectionA="",breakpointB="", strandB="", fusionDirectionB="",notes=myRow[8])
                    _data['fusions'].append(fusion)
                num+=1
         _data['genes']=sorted(_data['genes'], key=lambda gene: gene.name)
         _data['fusions']=sorted(_data['fusions'], key=lambda fusion: fusion.geneA)
         return _data
     
     def extractDataFromOMIM(self,sheet):
         _data={'genes':[],'fusions':[]}
         num=0
         for rownum in range(sheet.nrows):
                myRow = sheet.row_values(rownum)
                if num <1:
                    self._headers.append(myRow)
                else:
                    diseaseA=""
                    for disease in self._diseases:
                        if myRow[5].find(disease)!=-1:
                            diseaseA+= disease + " "
                    geneA =Model.Gene(myRow[2])
                    geneB =Model.Gene(myRow[4])
                    
                    _data['genes'].append(geneA)
                    _data['genes'].append(geneB)
                    fusion = Model.Fusion(myRow[2],myRow[4],breakpointA="", fusionDirectionA="",breakpointB="", strandB="", fusionDirectionB="",notes=diseaseA)
                    _data['fusions'].append(fusion)
                num+=1
         _data['genes']=sorted(_data['genes'], key=lambda gene: gene.name)
         _data['fusions']=sorted(_data['fusions'], key=lambda fusion: fusion.geneA)
         return _data
                
     def extractDataFromPubMed(self,sheet):
         _data={'genes':[],'fusions':[]}
         num=0
         for rownum in range(sheet.nrows):
                myRow = sheet.row_values(rownum)
                if num <1:
                    self._headers.append(myRow)
                else:
                    diseaseA=""
                    for disease in self._diseases:
                        if myRow[2].find(disease)!=-1:
                            diseaseA+= disease + " "
                    geneA =Model.Gene(myRow[0])
                    geneB =Model.Gene(myRow[1])
                    
                    _data['genes'].append(geneA)
                    _data['genes'].append(geneB)
                    fusion = Model.Fusion(myRow[0],myRow[1],breakpointA="", fusionDirectionA="",breakpointB="", strandB="", fusionDirectionB="",notes=diseaseA)
                    _data['fusions'].append(fusion)
                num+=1
         _data['genes']=sorted(_data['genes'], key=lambda gene: gene.name)
         _data['fusions']=sorted(_data['fusions'], key=lambda fusion: fusion.geneA)
         return _data
     def setData(self,data):
         self._data=data
    
     def getOptionPanel(self,parent):
         self.v = Tkinter.StringVar()
         self.y = Tkinter.StringVar()
         self.y.set(self._options['path'])
         self.optionPanelIn=ttk.Frame(parent)
         title = ttk.Label(self.optionPanelIn,text="PO Down")
         label0 = ttk.Label(self.optionPanelIn,text="Database file path:")
         ent0 = ttk.Entry(self.optionPanelIn,textvariable=self.y)
         
         browseBtn = ttk.Button(self.optionPanelIn, text="Browse...",command=self.browse)
         selectBtn = ttk.Button(self.optionPanelIn, text="OK",command=self.select)
         abortBtn = ttk.Button(self.optionPanelIn, text="Cancel",command=self.optionPanelIn.destroy)
         
         title.pack()
         label0.pack()
         ent0.pack(fill=Tkinter.X)
         browseBtn.pack()
         selectBtn.pack(fill=Tkinter.X)
         abortBtn.pack(fill=Tkinter.X)
         
         self.optionPanelIn.pack(side="top", fill="both", expand=1)
         return self.optionPanelIn
    
     def browse(self):
        dir_opt = options = {}
        options['initialdir'] = self.v.get()
        options['title'] = 'Select PO_down.xls:'
        options['parent'] = self.optionPanelIn
        directory=tkFileDialog.askopenfilename(**dir_opt)
        if directory != None and directory!="":
            self.y.set(directory)
         
     def select(self):
         self._options['path']=self.y.get()
         self.configDoneFunction()
             
     def setConfig(self,options):
         self._options=options
     
     def getConfig(self):
         return self._options




def openFile(path,mode):
     try:
         myFileobj = open(path,mode)
         return myFileobj
     except IOError:
             raise Exception('cannot open file')  
    